<?php

//date_default_timezone_set("America/New_York");
header('Content-Type: text/event-stream');
header('Cache-Control: no-store');
header('Connection: keep-alive');
header('Access-Control-Allow-Origin: *');
header('X-Accel-Buffering: no'); //nginx 关闭输出缓存

ob_end_flush();
ob_implicit_flush(1);

$lastEventId = floatval(isset($_SERVER['HTTP_LAST_EVENT_ID']) ? $_SERVER['HTTP_LAST_EVENT_ID'] : 0);
if (0 == $lastEventId) {
    $lastEventId = floatval(isset($_GET['lastEventId']) ? $_GET['lastEventId'] : 0);
}

output(str_repeat(' ', 2048), ''); // 2 kB padding for IE
output(2000, 'retry');

// event-stream
$i = $lastEventId;
$c = $i + 10;
while (++$i < $c) {
    output($i, 'id');
    output($i);
    
    ob_flush();
    flush();
    sleep(1);
}

function output($data, $type = 'data')
{
    if (is_array($data)) {
        $data = json_encode($data);
    }

    echo "$type:$data\n";
    if ('data' === $type) {
        echo "\n";
    }


}